﻿using System;
using System.Collections.Generic;
using System.Text;
using Csla.Core;
using Csla;
using Microsoft.Practices.EnterpriseLibrary.Data;
using System.Data.Common;
using System.Data;
using Csla.Data;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace buildingLib.fee
{
    public class FeeTemplate : BusinessBase<FeeTemplate>, security.IACL
    {
                #region ACL
        public Guid ACLID
        {
            get { return new Guid("{35DD499D-D333-45fb-A81B-24AF09F8D5DA}"); }
        }

        public string ACLName
        {
            get { return "财务模板编辑"; }
        }

        public string ACLCategory
        {
            get { return "财务"; }
        }

        public string ACLDescription
        {
            get { return "财务模板编辑"; }
        }

        public static Guid GetACLID()
        {
            return new Guid("{35DD499D-D333-45fb-A81B-24AF09F8D5DA}");
        }

        #endregion
        #region Bussiness
        Guid m_id = Guid.Empty;
        public Guid Id
        {
            get { return m_id; }
        }
        protected override object GetIdValue()
        {
            //throw new Exception("The method or operation is not implemented.");
            return m_id;
        }

        string m_name = string.Empty;
        public string Name {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_name;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_name != value)
                {
                    m_name = value;
                    PropertyHasChanged();
                }
            }
        }

        string m_memo = string.Empty;
        public string Memo
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_memo;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = string.Empty;
                if (m_memo != value)
                {
                    m_memo = value;
                    PropertyHasChanged();
                }
            }
        }

        bool m_type;
        public bool Type
        {
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            get
            {
                CanReadProperty(true);
                return m_type;
            }
            [System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.NoInlining)]
            set
            {
                CanWriteProperty(true);
                if (value == null) value = false;
                if (m_type != value)
                {
                    m_type = value;
                    PropertyHasChanged();
                }
            }
        }

        InvoiceItems m_items;
        public InvoiceItems Items
        {
            get { return m_items; }
        }
        #endregion

        #region Factory
        private FeeTemplate() { }
        static public FeeTemplate NewFeeTemplate(bool type)
        {
            return DataPortal.Create<FeeTemplate>(type);
        }

        static public FeeTemplate GetFeeTemplate(Guid id)
        {
            return DataPortal.Fetch<FeeTemplate>(id);
        }

        public static void DeleteRoot(Guid id)
        {
            DataPortal.Delete(new Criteria(id));
        }
        #endregion

        #region DataMethod
        [Serializable()]
        private class Criteria
        {
            private Guid _id;
            public Guid Id
            {
                get { return _id; }
            }
            public Criteria(Guid id)
            { _id = id; }
        }

        [RunLocal]
        protected void DataPortal_Create(object type)
        {
            //base.DataPortal_Create();
            m_id = Guid.NewGuid();
            m_type = (bool)type;
            m_items = InvoiceItems.NewInvoiceItems();
        }

        protected override void DataPortal_Fetch(object criteria)
        {
            //base.DataPortal_Fetch(criteria);

            Database db = SQLDatabase.GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand("select * from FeeTemplate Where id = @id");
            db.AddInParameter(cmd, "id", DbType.Guid, criteria);
            using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(cmd)))
            {
                if (dr.Read())
                {
                    m_id = dr.GetGuid("id");
                    m_name = dr.GetString("name");
                    m_memo = dr.GetString("memo");
                    m_type = dr.GetBoolean("type");
                    //读取二进制内容
                    System.IO.Stream sr = new MemoryStream();
                    int bufLen = 100;
                    byte[] b = new byte[bufLen];
                    BinaryWriter bw = new BinaryWriter(sr);
                    long startIndex = 0;
                    long retval;
                    retval = dr.GetBytes("sdata", startIndex, b, 0, bufLen);
                    while (retval == bufLen)
                    {
                        bw.Write(b);
                        bw.Flush();

                        startIndex += bufLen;
                        retval = dr.GetBytes("sdata", startIndex, b, 0, bufLen);
                    }
                    bw.Write(b);
                    sr.Position = 0;
                    //反序列化
                    BinaryFormatter formatter = new BinaryFormatter();
                    m_items = formatter.Deserialize(sr) as InvoiceItems;
                    sr.Close();
                }
            }
        }

        protected override void DataPortal_Insert()
        {
            //base.DataPortal_Insert();
            string sql = "Insert Into feeTemplate Values(@id,@name,@memo,@erased,@sdata,@type)";
            Database db = SQLDatabase.GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);
            db.AddInParameter(cmd,"id",DbType.Guid,m_id);
            db.AddInParameter(cmd, "name", DbType.String, m_name);
            db.AddInParameter(cmd, "memo", DbType.String, m_memo);
            db.AddInParameter(cmd, "erased", DbType.Boolean, false);
            
            db.AddInParameter(cmd, "type", DbType.Boolean, m_type);

            //序列化
            System.IO.Stream sData = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(sData, m_items);
            byte[] bData = new byte[sData.Length];
            sData.Position = 0;
            sData.Read(bData, 0, (int)sData.Length);
            sData.Close();
            db.AddInParameter(cmd, "sdata", DbType.Binary, bData);
            db.ExecuteNonQuery(cmd);
        }

        public void Update()
        {
            //base.DataPortal_Update();

            string sql = "Update FeeTemplate Set name=@name,memo=@memo,sdata=@sdata,type=@type where id = @id";
            Database db = SQLDatabase.GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);

            db.AddInParameter(cmd, "id", DbType.Guid, m_id);
            db.AddInParameter(cmd, "name", DbType.String, m_name);
            db.AddInParameter(cmd, "memo", DbType.String, m_memo);
            db.AddInParameter(cmd, "erased", DbType.Boolean, false);

            db.AddInParameter(cmd, "type", DbType.Boolean, m_type);

            //序列化
            System.IO.Stream sData = new MemoryStream();
            BinaryFormatter bf = new BinaryFormatter();
            bf.Serialize(sData, m_items);
            byte[] bData = new byte[sData.Length];
            sData.Position = 0;
            sData.Read(bData, 0, (int)sData.Length);
            sData.Close();
            db.AddInParameter(cmd, "sdata", DbType.Binary, bData);
            db.ExecuteNonQuery(cmd);
        }

        protected override void DataPortal_DeleteSelf()
        {
            string sql = "Update FeeTemplate Set erased=1 where id = @id";
            Database db = SQLDatabase.GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);

           // db.AddInParameter(cmd, "id", DbType.Guid, id);
            db.ExecuteNonQuery(cmd);
        }



        private void DataPortal_Delete(Criteria criteria)
        {

            string sql = "Update FeeTemplate Set erased=1 where id = @id";
            Database db = SQLDatabase.GetDatabase();
            DbCommand cmd = db.GetSqlStringCommand(sql);

            db.AddInParameter(cmd, "id", DbType.Guid, criteria.Id);
            db.ExecuteNonQuery(cmd);
        }
        #endregion
    }

    //public class FeeTemplateList : BusinessListBase<FeeTemplateList, FeeTemplate>
    //{
    //    #region Factory Method
    //    private FeeTemplateList() { }
    //    static public FeeTemplateList GetFeeTemplateList(string where)
    //    {
    //        FeeTemplateList templateList = new FeeTemplateList();
    //        templateList.Fetch(where);
    //        return templateList;
    //    }
    //    #endregion
    //    #region DataMthod
    //    public void Fetch(string where)
    //    {
    //        string sql = "Select id from feetemplate where ";
    //        sql += where + "erased=0";
    //        Database db = SQLDatabase.GetDatabase();
    //        DbCommand cmd = db.GetSqlStringCommand(sql);
    //        using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(cmd)))
    //        {
    //            while (dr.Read())
    //            {
    //                this.Add(FeeTemplate.GetFeeTemplate(dr.GetGuid("id")));
    //            }
    //        }
    //    }
    //    #endregion
    //}

    public class FeeTemplateList : NameValueListBase<Guid, string>
    {

        static FeeTemplateList m_List;
        public static FeeTemplateList GetLists(string condition)
        {
            return DataPortal.Fetch<FeeTemplateList>(new Criteria(condition));
        }

        public static void InvalidateCache()
        {
            m_List = null;
        }

        class Criteria
        {
            string m_condition;
            public string Condition
            {
                get { return m_condition; }
            }
            public Criteria(string condition)
            {
                m_condition = condition;
            }
        }

        private FeeTemplateList() { }
        #region DataAccess

        protected override void DataPortal_Fetch(object criteria)
        {
            RaiseListChangedEvents = false;
            IsReadOnly = false;
            string sql = "Select id,Name from feetemplate where ";
            sql += ((Criteria)criteria).Condition + "erased=0";
            Database db = SQLDatabase.GetDatabase();
            DbCommand dbcom = db.GetSqlStringCommand(sql);

            using (SafeDataReader dr = new SafeDataReader(db.ExecuteReader(dbcom)))
            {
                while (dr.Read())
                {
                    Add(new NameValueListBase<Guid, string>.
                      NameValuePair(dr.GetGuid("id"), dr.GetString("name")));
                }
            }
            IsReadOnly = true;
            RaiseListChangedEvents = true;
        }
        #endregion
    }
}
